package com.example.DataSource.ServiceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.DataSource.Mapper.LoginMapper;
import com.example.DataSource.Service.LoginService;
import com.example.DataSource.entity.consultant;
import com.example.DataSource.entity.member;
import com.example.DataSource.entity.user;
import com.example.DataSource.entity.userLogin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

import com.example.DataSource.Mapper.memberMapper;
import com.example.DataSource.Mapper.consultantMapper;

@Service
public class LoginServiceImpl extends ServiceImpl<LoginMapper, userLogin> implements LoginService {

    @Autowired
    private LoginMapper loginMapper;
    @Autowired
    private memberMapper memberMapper;
    @Autowired
    private consultantMapper consultantMapper;

    @Transactional(rollbackFor = Exception.class)
    public String register(user registerUser) {
        QueryWrapper<userLogin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("UserName", registerUser.getUserName());
        List<userLogin> list = loginMapper.selectList(queryWrapper);
        if (!list.isEmpty()) {
            return "该用户已经存在，请换个用户名";
        }

        userLogin userLogin = new userLogin();
        userLogin.setUserName(registerUser.getUserName());
        userLogin.setPwd(registerUser.getPwd());
        loginMapper.insert(userLogin);

        if (registerUser.getType() == 0) { // 会员
            member member = new member();
            member.setUsername(registerUser.getUserName());
            member.setPassword(String.valueOf(registerUser.getPwd()));
            // 设置其他会员表需要的字段
            memberMapper.insert(member);
        } else if (registerUser.getType() == 1) { // 管理员
            consultant consultant = new consultant();
            consultant.setUsername(registerUser.getUserName());
            consultant.setPassword(String.valueOf(registerUser.getPwd()));
            // 设置其他管理员表需要的字段
            consultantMapper.insert(consultant);
        }

        return "success";
    }
}
